<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3.vue3响应式</title>
  </head>
  <body>
    <script>

      function reactive(target = {}) {
        if (typeof target !== "object") {
          return target;
        }

        // 代理配置
        const proxyConfig = {
          get(target, key, proxyObj) {
            const ownKeys = Reflect.ownKeys(target);
            if (ownKeys.includes(key)) {
              console.log("get", key);
            }
            const result = Reflect.get(target, key, proxyObj);
            // 深度监听，用的时候才递归保证了性能
            return reactive(result); //
          },
          set(target, key, val, proxyObj) {
            // 重复的数据不处理
            if (val === target[key]) {
              return true;
            }
            const ownKeys = Reflect.ownKeys(target);
            if (ownKeys.includes(key)) { // 
              console.log("已存在的key", key);
            }else{
              console.log("新增的key", key);
            }
            const result = Reflect.set(target, key, val, proxyObj);
            console.log("set", key, val);
            return result;
          },
          deleteProperty(target, key) {
            const result = Reflect.deleteProperty(target, key);
            console.log("delete", key);
            return result;
          }
        };

        //生成代理对象
        const observed = new Proxy(target, proxyConfig);
        return observed;
      }

      const data = {
        name: "zs",
        age: 20
      };

      const proxyData = reactive(data);
      console.log(proxyData)
      proxyData.age;
      proxyData.age2 = 33;
      proxyData.obj = { a: 1 };
      proxyData.obj.a = 2;
    </script>
  </body>
</html>
